<script setup lang="ts">
import { ref, watch } from 'vue'
import { Article, ApiRes } from '../types/data'
import axios from 'axios'
import dayjs from 'dayjs'
import relativeTime from 'dayjs/plugin/relativeTime'
import 'dayjs/locale/zh-cn'
dayjs.extend(relativeTime)
dayjs.locale('zh-cn') // 中文
const list = ref<Article[]>([])
const props = defineProps<{ channelId: number }>()
// 发请求：会调用多次（第一次要调用、后面channnelId变了，要调用）
const getData = async () => {
  // console.log('---props---', props.channelId)
  /**
   * axios.get<响应体的类型>
   */
  const res = await axios.get<
    ApiRes<{ pre_timestamp: string; results: Article[] }>
  >(
    `http://geek.itheima.net/v1_0/articles?channel_id=${
      props.channelId
    }&timestamp=${Date.now()}`
  )

  list.value = res.data.data.results
}
// 如果一上来要发请求，后面id变了，也要发请求，就用watch
/**
 * 参数1：如果要监听响应式对象props中的某个属性，要写成箭头函数的形式
 */
watch(
  () => props.channelId,
  () => {
    getData()
  },
  {
    immediate: true
  }
)
</script>

<template>
  <div class="article-list">
    <div class="article-item" v-for="item in list" :key="item.art_id">
      <p class="title">
        {{ item.title }}
      </p>
      <img
        v-for="(img, i) in item.cover.images"
        class="img"
        :src="img"
        alt=""
        :key="i"
      />
      <div class="info">
        <span>{{ item.aut_name }}</span>
        <span>{{ item.comm_count }}评论</span>
        <span>{{ dayjs(item.pubdate).fromNow() }}</span>
      </div>
    </div>
  </div>
</template>
